<?php

namespace App\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 项目下的参建单位
 * Class PartCompany
 */
class PartCompany extends Model
{
    use SoftDeletes;

    protected $guarded = ['id'];

    const TYPE = [
        0 => '未知',
        1 => '业主单位',
        2 => '监理单位',
        3 => '施工单位',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 关联关系 1:N 检索参建单位下的部门
     * @return HasMany
     */
    public function departments(): HasMany
    {
        return $this->hasMany(Department::class);
    }

    /**
     * 关联关系 N:N 检索配置在参建单位下的用户
     * @return BelongsToMany
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'part_company_user')->withPivot('creator_id'); //获取中间表字段
    }

    /**
     * 关联关系 1:N 检索参建单位所属项目
     * @return BelongsTo
     */
    public function project(): BelongsTo
    {
        return $this->belongsTo(Project::class);
    }

    /**
     * 参建单位和项目分类
     */
    public function classify()
    {
        return $this->belongsToMany(ProjectClassify::class, 'part_company_classify', 'part_company_id', 'project_classify_id');
    }

    public function projectClassifyId ()
    {
        return $this->belongsToMany(ProjectClassify::class, 'sort_links', 'part_company_id', 'project_classify_id');
    }
}
